package com.snap.vseries.ui.widget;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.bean.SerialPortDevice;
import com.snap.vseries.framework.MoleExecutor;
import com.snap.vseries.framework.MoleTask;
import com.snap.vseries.update.UpdateCmd;
import com.snap.vseries.update.UpdateSerialPortHelper;
import com.snap.vseries.utils.TopTitleUtils;

import java.io.IOException;

import butterknife.BindView;

import static com.snap.vseries.AppConfig.SERIAL_BAUD_RATE;
import static com.snap.vseries.AppConfig.SERIAL_PORT;

/**
 * @author Rachel
 */
public class DeviceDetailActivity extends BaseActivity {
    @BindView(R.id.hardware_version_tv)
    TextView hardwareVersionTv;
    private int deviceId;


    @Override
    protected int layoutResId() {
        return R.layout.activity_device_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        deviceId = Integer.parseInt(getIntent().getStringExtra("deviceId"));
        new TopTitleUtils(this).setTitle("设备详情");


        MoleExecutor.getInstance().execute(new MoleTask<String>() {
            @Override
            public String runInBackground() throws InterruptedException {
                String res = null;
                UpdateSerialPortHelper serialPortHelper = new UpdateSerialPortHelper(new SerialPortDevice(SERIAL_PORT, SERIAL_BAUD_RATE));
                try {
                    serialPortHelper.open();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Bundle b = serialPortHelper.execute(UpdateCmd.getHardInfo(deviceId));
                if (b.getBoolean("suc")) {
                    byte[] data = b.getByteArray("data");
                    if (data != null) {
                        int v1 = data[11];
                        int v2 = data[12];
                        int v3 = data[13];
                        res = v1 + "." + v2 + "." + v3;
                    }
                }
                serialPortHelper.close();
                return res;
            }

            @Override
            public void onCompleted(String result) {
                if (hardwareVersionTv != null) {
                    hardwareVersionTv.setText(result == null ? "" : String.format("v%s", result));
                }
            }
        });
    }
}